﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using IntelligentDecisioning.SharePoint.Logging;
using Microsoft.SharePoint.Utilities;

namespace IntelligentDecisioning.SharePoint.Helpers
{
    /// <summary>
    /// Base class for our helper library. Use to factor out
    /// common code and to implement the IDisposable design pattern
    /// allowing use to clean up the SPWeb and SPSite objects. Dont call Dispose()
    /// if you intended to use thes obhects outside the helper class !!
    /// </summary>
    public class IDSharePointHelper: IDisposable
    {
        #region Data

        protected SPSite SiteCollection { get; private set; }
        protected SPWeb RootWeb { get; private set; }
        protected SPWeb TargetWeb { get; set; }
        protected ILog Log { get; private set; }

        #endregion

        #region Constructor

        public IDSharePointHelper(SPSite siteCollection, SPWeb targetWeb, ILog log)
        {
            if (siteCollection == null) throw new ArgumentNullException("Site Collection");
            if (targetWeb == null) throw new ArgumentNullException("Target web");

            SiteCollection = siteCollection;
            RootWeb = siteCollection.RootWeb;
            TargetWeb = targetWeb;
            Log = log;
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            try
            {
                if (SiteCollection != null) SiteCollection.Dispose();
            }
            catch{}

            try
            {
                if (RootWeb != null) RootWeb.Dispose();
            }
            catch{}

            try
            {
                if (TargetWeb != null) TargetWeb.Dispose();
            }
            catch { }
        }

        #endregion

        #region Shared Methods

        public bool SendEmail(SPUser user, string subject, string body)
        {
 
            bool success = false;
            try
            {

                string toField = user.Email;
                success = SPUtility.SendEmail(TargetWeb, true, true, toField, subject, body);
            }
            catch { }

            return success;
        }


        #endregion
    }
}
